<!--  -->
<template>
  <div>
    <el-card style="margin: 20px">
      <el-form :inline="true" :model="querys" class="demo-form-inline">
        <el-form-item label="姓名/电话">
          <el-input v-model="querys.query" placeholder="请输入搜索关键字" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getAdminList">查询</el-button>
          <el-button v-hasPermi="['/admin/saveAdmin']" type="primary" icon="el-icon-circle-check" @click="addAdmin">添加</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card  style="margin: 0px 20px">
      <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        @sort-change="sortChange"
      >
        <el-table-column prop="id" label="ID" width="100" align="center" sortable="custom" :class-name="getClass('id')" />
        <el-table-column prop="name" label="姓名" width="200" align="center" sortable="custom" :class-name="getClass('name')" />
        <el-table-column prop="phone" label="手机号码" width="200" align="center" sortable="custom" :class-name="getClass('phone')" />
        <el-table-column prop="address" label="联系地址" width="300" align="center" sortable="custom" :class-name="getClass('address')" />
        <el-table-column prop="state" label="状态" width="200" sortable="custom" :class-name="getClass('state')" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="stateChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="200" align="center" sortable="custom" :class-name="getClass('username')" />
        <el-table-column prop="remark" label="备注" width="100" align="center" />
        <el-table-column prop="state" label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button v-has-permi="['/admin/saveAdmin']" type="success" icon="el-icon-edit" @click="editAdmin(scope.row)" />
              <el-button v-has-permi="['/adminRole/addListAdminRole']" type="success" icon="el-icon-share" @click="roleAdmin(scope.row)" />
              <el-button v-has-permi="['/admin/delAdmin/**']" type="success" icon="el-icon-delete" @click="delAdmin(scope.row)" />
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="querys.pageIndex"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="querys.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-dialog title="分配角色" :visible.sync="AdminRoleVisible" width="500px">
        <el-form :model="adminRoleForm" label="角色名">
          <el-form-item>
            <el-tree
              ref="roleTree"
              v-model="adminRoleForm.rid"
              :data="roles"
              show-checkbox
              :default-checked-keys="treeCheckedKey"
              default-expand-all
              node-key="id"
              highlight-current
              :props="defaultProps"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAdminRoleForm">取 消</el-button>
          <el-button v-has-permi="['/adminRole/addListAdminRole']" type="primary" @click="confirmAdminRoleForm">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="opr+'操作员'" :visible.sync="AdminFormVisible">
        <el-form ref="adminForm" :model="AdminForm" :rules="AdminRules">
          <el-form-item label="名称" prop="name" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="AdminForm.name" autocomplete="off" placeholder="请输入名称..." />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="AdminForm.phone" autocomplete="off" placeholder="请输入手机号码..." />
          </el-form-item>
          <el-form-item label="住宅电话" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="AdminForm.telephone" autocomplete="off" placeholder="请输入住宅电话..." />
          </el-form-item>
          <el-form-item label="用户名" prop="username" :label-width="formLabelWidth" style="display: inline-block">
            <el-input v-model="AdminForm.username" autocomplete="off" placeholder="请输入用户名..." />
          </el-form-item>
          <el-form-item
            v-if="AdminForm.id===0"
            label="密码"
            prop="password"
            :label-width="formLabelWidth"
            style="display: inline-block"
          >
            <el-input v-model="AdminForm.password" autocomplete="off" placeholder="请输入密码..." />
          </el-form-item>
          <el-form-item
            v-if="AdminForm.id===0"
            label="确认密码"
            prop="confimPassword"
            :label-width="formLabelWidth"
            style="display: inline-block"
          >
            <el-input v-model="AdminForm.confimPassword" autocomplete="off" placeholder="请输入确认密码..." />
          </el-form-item>
          <el-form-item label="用户头像" :label-width="formLabelWidth">
            <el-input v-model="AdminForm.userFace" style="display: none" class="id" />
            <single-upload v-model="AdminForm.userFace" />
          </el-form-item>
          <el-form-item label="联系地址" :label-width="formLabelWidth">
            <el-input v-model="AdminForm.address" autocomplete="off" placeholder="请输入联系地址..." />
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input
              v-model="AdminForm.remark"
              type="textarea"
              placeholder="请输入描述..."
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeAdminForm">取 消</el-button>
          <el-button type="primary" @click="confirmAdminForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

import { delAdmin, getAdminById, getList, saveAdmin } from '@/api/user'
import { getRoleList, addadminRole, getRoleListByAdminId } from '@/api/role'
import singleUpload from '@/components/upload/singleUpload.vue'

export default {

  components: {
    singleUpload
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      const reg = /^[1][3-9][0-9]{9}$/
      // eslint-disable-next-line eqeqeq
      if (value == '' || value == undefined || value == null) {
        callback()
      } else {
        // eslint-disable-next-line eqeqeq
        if ((!reg.test(value)) && value != '') {
          callback(new Error('请输入正确的电话号码'))
        } else {
          callback()
        }
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (this.AdminForm.password === this.AdminForm.confimPassword) {
        callback()
      } else {
        callback(new Error('两次输入的密码不一致'))
      }
    }
    return {
      tableData: [],
      querys: { pageIndex: 1, pageSize: 2, sort: 'ascending_id', query: '' },
      total: 0,
      AdminForm: {
        id: 0,
        name: '',
        phone: '',
        telephone: '',
        address: '',
        state: 1,
        username: '',
        password: '',
        confimPassword: '',
        userFace: '',
        remark: ''
      },
      opr: '新增',
      AdminFormVisible: false,
      formLabelWidth: '180px',
      AdminRules: {
        name: [{ required: true, message: '姓名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名的长度在2~10个字符之间', trigger: 'blur' }],
        phone: [{ required: true, message: '密码必填', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }],
        username: [{ required: true, message: '登录名必填', trigger: 'blur' },
          { min: 2, max: 10, message: '登录名的长度在2~10个字符之间', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '密码长度在3~15位之间', trigger: 'blur' }],
        confimPassword: [{ required: true, message: '确认密码必填', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }]
      },
      AdminRoleVisible: false,
      defaultProps: { label: 'nameZh' },
      treeCheckedKey: [],
      roles: [],
      adminRoleForm: { adminId: '', rid: [] }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getAdminList()
    this.getRoleList()
  },
  // 方法集合
  methods: {
    addAdmin() {
      this.clearAdminForm()
      this.AdminFormVisible = true
    },
    getRoleList() {
      getRoleList().then((res) => {
        this.roles = res.data
        console.log('角色列表', this.roles)
      })
    },
    closeAdminRoleForm() {
      this.adminRoleForm = { adminId: '', rid: [] }
      this.treeCheckedKey = []
      this.AdminRoleVisible = false
    },
    confirmAdminRoleForm() {
      this.adminRoleForm.rid = this.$refs.roleTree.getCheckedKeys()
      addadminRole(this.adminRoleForm).then((res) => {
        this.getAdminList()
        this.closeAdminRoleForm()
      })
    },
    delAdmin(admin) {
      delAdmin(admin.id).then((res) => {
        this.getAdminList()
      })
    },
    roleAdmin(admin) {
      console.log('分配角色', admin)
      this.AdminRoleVisible = true
      this.adminRoleForm.adminId = admin.id
      getRoleListByAdminId(admin.id).then((res) => {
        if (res.data.rid) {
          this.treeCheckedKey = res.data.rid
        }
      })
    },
    editAdmin(admin) {
      getAdminById(admin.id).then((res) => {
        this.opr = '修改'
        this.AdminForm = res.data
        this.AdminFormVisible = true
      })
    },
    stateChange(admin) {
      console.log(admin)
      saveAdmin(admin).then((res) => {
        this.getAdminList()
      })
    },
    closeAdminForm() {
      this.clearAdminForm()
      this.AdminFormVisible = false
      this.AdminForm = { id: 0, name: '', phone: '', telephone: '', address: '', state: 1, username: '', password: '', confimPassword: '', userFace: '', remark: '' }
    },
    confirmAdminForm() {
      this.$refs.adminForm.validate((valid) => {
        if (valid) {
          saveAdmin(this.AdminForm).then((res) => {
            this.getAdminList()
            this.closeAdminForm()
          })
        }
      }
      )
    },
    getAdminList() {
      getList(this.querys).then((res) => {
        this.tableData = res.data.records
        this.total = res.data.total
        console.log(res)
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    clearAdminForm() {
      this.AdminForm = { id: 0, name: '', phone: '', telephone: '', address: '', state: 1, username: '', password: '', confimPassword: '', userFace: '', remark: '' }
      this.opr = '添加'
    },
    handleSizeChange(val) {
      this.querys.pageSize = val
      this.getAdminList()
    },
    handleCurrentChange(val) {
      this.querys.pageIndex = val
      this.getAdminList()
    },
    sortChange(data) {
      this.sortBy(data.order, data.prop)
    },
    sortBy(order, prop) {
      if (order === 'ascending') {
        this.querys.sort = 'ascending_' + prop
      } else {
        this.querys.sort = 'descending_' + prop
      }
      this.querys.pageIndex = 1
      this.getAdminList()
    },
    getClass(key) {
      const sort = this.querys.sort
      return sort === `ascending_${key}` ? 'ascending' : 'descending'
    }
  } // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
